package com.my.learn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) throws IOException {
        //创建选择器
        Selector selector = Selector.open();
        //打开服务器套接字通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //将选择器注册到socket用来接受连接
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        ServerSocket serverSocket = serverSocketChannel.socket();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
        serverSocket.bind(address);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()) {
                SelectionKey key = selectionKeyIterator.next();
                if (key.isAcceptable()) {
                    ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel1 = socketChannel.accept();
                    socketChannel1.configureBlocking(false);
                    // 这个新连接主要用于从客户端读取数据
                    socketChannel1.register(selector, SelectionKey.OP_READ);
                    System.out.println(socketChannel1.getRemoteAddress() + "进行连接");
                } else if (key.isReadable()) {
                    SocketChannel sChannel = (SocketChannel) key.channel();
                    System.out.println(sChannel.getRemoteAddress() + ": " + readDataFromSocketChannel(sChannel));
                    sChannel.close();
                }
                System.out.println("size:" + selector.keys().size());
                selectionKeyIterator.remove();
            }
        }

    }

    private static String readDataFromSocketChannel(SocketChannel sChannel) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        StringBuffer stringBuffer = new StringBuffer();
        while (true) {
            byteBuffer.clear();
            while (sChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                int n = byteBuffer.limit();
                stringBuffer.append(new String(byteBuffer.array(), 0, n));
                byteBuffer.clear();
            }
            break;
        }
        return stringBuffer.toString();
    }

}
